package weibo.service;

import java.io.IOException;
import java.util.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.*;

import weibo.database.PraiseDB;
import weibo.database.TweetDB;
import weibo.model.UserMod;

/**
 * Servlet implementation class userinfo
 */
@WebServlet("/userinfo")
public class userinfo extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public userinfo() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		//登录控制
				HttpSession session=request.getSession();
				List<UserMod> user=(List<UserMod>) session.getAttribute("user");
				if (user==null){
					response.setCharacterEncoding("utf8");
					response.setContentType("text/html;");
					response.getWriter().append("未登录，请点击 	 <a href='./userlogin'>登录</a>");
				}else{
					request.getRequestDispatcher("./userinfo.html").forward(request, response);
				}
		
	}

	/**
	 * 获取用户信息
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//doGet(request, response);
		response.setCharacterEncoding("UTF-8");
		HttpSession session=request.getSession();
		List<UserMod> user=(List<UserMod>) session.getAttribute("user");
		if (user!=null){
			JSONObject userinfo=new JSONObject();
			TweetDB db=new TweetDB();
			PraiseDB praise=new PraiseDB();
			int value=db.SelectTweetUserCount(user.get(0).getUserid());
			int praisevalue=praise.QueryPraiseUserCount(user.get(0).getUserid());
			userinfo.put("tweet_number", value);
			userinfo.put("praise_number", praisevalue);
			userinfo.put("id",user.get(0).getUserid());
			userinfo.put("login_name",user.get(0).getLogin_name());
			userinfo.put("user_name",user.get(0).getUser_name());
			userinfo.put("sex",user.get(0).getSex());
			userinfo.put("borndate",user.get(0).getBorndate());
			userinfo.put("create_date",user.get(0).getCreate_date());
			userinfo.put("simple",user.get(0).getSimple());
			userinfo.put("user_head",user.get(0).getUser_head());
			response.getWriter().append(userinfo.toString());
			System.out.println(user.get(0).getLogin_name()+" 用户请求获取用户信息");
		}else{
			response.getWriter().append("error");
			System.out.println("用户未登录,却请求了用户信息");
		}
		
	}

}
